import { toSuccess, useEntityManager } from "@sker/core"
import { KsDevice, KsLiveRoomDayLog, KsLiveRoomLog } from "@sker/entities"
import { useReqQuery } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"


export default async () => {
    const input = z.object({
        d: z.optional(z.string())
    })
    const body = input.parse(useReqQuery())
    return await useEntityManager(async m => {
        const dayInt = parseInt(`${body.d || '0'}`)
        const qb = m.createQueryBuilder()
            .select('log.count', 'count')
            .addSelect('device.owner', 'owner')
            .addSelect('log.uuid', 'uuid')
            .from(KsLiveRoomLog, 'log')
            .leftJoin(KsDevice, 'device', 'device.uuid=log.uuid')
            .where('log.create_date>:start_date', { start_date: dayjs().subtract(dayInt, 'day').startOf('day').toDate() })
            .andWhere('log.create_date<:end_date', { end_date: dayjs().subtract(dayInt, 'day').endOf('day').toDate() })
            .andWhere('log.count>:count', { count: 0 })
        const list = await qb.execute()
        const total: any = {}
        const device: any = {}
        const owner: any = {}
        list.map(item => {
            const t = total[item.owner] || 0;
            const d = device[item.uuid] || 0;
            device[item.uuid] = d + item.count
            total[item.owner] = t + item.count
            owner[item.uuid] = item.owner;
        })
        const d = dayjs().subtract(dayInt, 'day')
        const year = d.get('year')
        const month = d.get('month') + 1;
        const day = d.get('date')
        const pkg = `com.smile.gifmaker`;
        await Promise.all(Object.keys(device).map(async uuid => {
            const d = device[uuid]
            const o = owner[uuid]
            const log = await m.findOne(KsLiveRoomDayLog, { where: { uuid: uuid, year: `${year}`, month: `${month}`, day: `${day}`, pkg } })
            const item = m.create(KsLiveRoomDayLog, {
                id: log?.id,
                uuid,
                year: `${year}`,
                month: `${month}`,
                day: `${day}`,
                pkg,
                owner: o,
                count: d
            })
            await m.save(KsLiveRoomDayLog, item)
        }))
        return toSuccess({ total, device, year, month, day, pkg })
    })
}